﻿using System;
using System.Configuration;

namespace MongoCamp
{
    /// <summary>
    /// MongoCamp Config 
    /// </summary>
    public class MongoSetting
    {
        /// <summary>
        ///  MongoCamp Config 
        /// </summary>
        /// <param name="connectionStringConfigKey">connectionStringConfigName</param>
        /// <param name="dbNameConfigKey">dbNameConfigName</param>
        public MongoSetting(string connectionStringConfigKey, string dbNameConfigKey)
        {
            ConnectionString = GetAppSetting(connectionStringConfigKey);
            DBName = GetAppSetting(dbNameConfigKey);
        }

        /// <summary>
        /// current connectionstring
        /// </summary>
        public string ConnectionString { get; private set; }

        // ReSharper disable once InconsistentNaming
        /// <summary>
        /// current database name
        /// </summary>
        public string DBName { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbKeyName">dbConfigName</param>
        /// <returns></returns>
        public static MongoSetting FromAppSetting(string dbKeyName)
        {
            return new MongoSetting(string.Format(ConnectionStringConfigFormat, dbKeyName),
                                   string.Format(DbNameConfigFormat, dbKeyName));
        }

        /// <summary>
        /// 数据库连接字符串配置格式 MongoCamp.{0}.ConnectionString
        /// </summary>
        public const string ConnectionStringConfigFormat = "MongoCamp.{0}.ConnectionString";
        /// <summary>
        /// 数据库名称配置格式 MongoCamp.{0}.DBName
        /// </summary>
        public const string DbNameConfigFormat = "MongoCamp.{0}.DBName";

        /// <summary>
        /// Get AppSetting's config from Web.Config/App.Config
        /// </summary>
        /// <param name="configName">key name</param>
        /// <returns>string</returns>
        public static string GetAppSetting(string configName)
        {
            var value = ConfigurationManager.AppSettings[configName];
            return string.IsNullOrEmpty(value) ? string.Empty : value;
        }
    }
}